<?php


namespace App\Http\Controllers\Wechat;


use App\Http\Controllers\Controller;
use App\Jobs\AutomaticSplitJob;
use App\Jobs\ManualSplitJob;
use App\Models\ElectricAccountingRecords;
use App\Models\ElectricPaymentOrder;
use App\Models\FleaOrder;
use App\Models\User;
use App\Models\Users;
use App\Services\NotifyService;
use App\Services\OrderCommentService;
use App\Services\SmsService;
use App\Services\SplitService;
use App\Services\UserService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class ServerController extends Controller
{

    /**
     * 用户注册
     * @param UserService $user_service
     * @return array
     * @author ypp
     * @date XXX
     */
    public function register(UserService $user_service)
    {
        // $app = app('wechat.mini_program');
        $res = $user_service->registerMini();
        if ($res['status']) {
            return $this->success($res['data']);
        } else {
            return $this->error($res['msg']);
        }

    }

    /**
     * @param $id int 用户ID
     * @return array | mixed
     * 通过ID获取用户信息
     */
    public function getUserData($id)
    {
        $is_login = auth('user')->check();

        if ($is_login) {
            $data = User::query()->select('id', 'nickname', 'avatar', 'sex', 'phone', 'user_intro')->find($id);

            return $this->success($data);
        }
    }

    /**
     * 发送短信
     * @param Request $request
     * @return array
     */
    public function send_sms(Request $request): array
    {
        $sms_service = new SmsService();
        $rs = $sms_service->sendSms($request->phone, $request->name);
        return $rs['status'] ? $this->success($rs['data'], $rs['msg']) : $this->error($rs['msg']);
    }


    /**
     * 微信小程序授权回调接口
     * TODO：公共回调接口 请提交支付时添加自定义参数 判断是哪种业务场景
     */
    public function wechatNotify()
    {
        $pay = app('wechat_pay');
        try {
            //验签
            $data = $pay->verify();
            $wxData = $data->only(['attach', 'out_trade_no', 'transaction_id', 'time_end', 'result_code', 'return_code', 'total_fee']);
            /**
             * 参数说明
             * $wxData['attach'] == 自定义参数 json格式的字符串
             * out_trade_no 单号
             * transaction_id 微信的单号
             * time_end  支付时间
             * total_fee 用户支付的金额
             */
            $param = json_decode($wxData['attach'], true);
            $type = $param['type'] ?? '';
            //必须判断微信支付是否返回SUCCESS
            if ($wxData['result_code'] == 'SUCCESS' && $wxData['return_code'] == 'SUCCESS') {
                switch ($type) {
                    //跳蚤市场的订单
                    case 'flea':
                        FleaOrder::updateOrder($wxData);
                        break;
                }
            }
        } catch (\Exception $e) {
            Log::error('Pay notify', [$e->getMessage()]);
            echo 'ERROR';
            die();
        }
        return $pay->success();
    }

    /**
     * 微信小程序授权回调接口
     * TODO：公共回调接口 请提交支付时添加自定义参数 判断是哪种业务场景
     */
    public function FeeNotify()
    {

        $pay = app('wechat_server');
        try {
//            //验签
            $data = $pay->verify();
            $wxData = $data->only(['out_trade_no', 'transaction_id', 'time_end', 'result_code', 'return_code', 'total_fee']);
            /**
             * 参数说明
             * $wxData['attach'] == 自定义参数 json格式的字符串
             * out_trade_no 单号
             * transaction_id 微信的单号
             * time_end  支付时间
             * total_fee 用户支付的金额
             */
            //必须判断微信支付是否返回SUCCESS
            $this->notify_handle($wxData);
        } catch (\Exception $e) {
            Log::error('Pay notify', [$e->getMessage()]);

            echo 'ERROR';
            die();
        }
        return $pay->success();
    }

    /**
     * 2021/3/22--11:32
     * @effect:普通商户微信支付回调
     * @author:苏冬冬
     * @QQ:1299273928
     * @method:payNotify
     * @return mixed
     */
    public function payNotify()
    {
        $pay = app('wechat_ordinary_merchant');
        try {
//            //验签
            $data = $pay->verify();
            $wxData = $data->only(['out_trade_no', 'transaction_id', 'time_end', 'result_code', 'return_code', 'total_fee']);
            /**
             * 参数说明
             * $wxData['attach'] == 自定义参数 json格式的字符串
             * out_trade_no 单号
             * transaction_id 微信的单号
             * time_end  支付时间
             * total_fee 用户支付的金额
             */
            //必须判断微信支付是否返回SUCCESS
            $this->notify_handle($wxData);
        } catch (\Exception $e) {
            Log::error('Pay notify', [$e->getMessage()]);

            echo 'ERROR';
            die();
        }
        return $pay->success();
}
    /**
     * 2021/3/19--11:23
     * @effect:分账操作
     * @param $one_order
     * @author:苏冬冬
     * @QQ:1299273928
     * @method:split_do
     */
    public static function split_do($one_order): void
    {
        $arr = json_encode([
            'orderNo' => $one_order['orderNo'],
            'create_at' => time(),
            'pay_type' => $one_order['pay_type'],
        ], JSON_THROW_ON_ERROR);
        extract($one_order, null);
        /**
         * @var $orderNo |订单编号
         * @var $user_id |来源用户
         * @var $fatherId |代理商id
         * @var $split_money |分账金额
         * @var $pay_type |支付方式
         * @var $handlingFee |手续费
         * @var $after_split |分帐后金额
         * @var $split_type |分账模式
         * @var $is_examine |是否需要审核：0，否；1，是
         * @var $room_number |房间号
         */
        switch ($split_type) {
            case 1://无分账
                break;
            case 2://自动分账

                try {
                    $insert_id = SplitService::insert_split_log($fatherId, $split_money, $room_number, $pay_type, $orderNo, $handlingFee, $after_split, $user_id, $split_type);//生成分账记录
                    AutomaticSplitJob::dispatch($arr)->onQueue('AutomaticSplitJob')->delay(now()->addMinutes(1.5)->timestamp);
                } catch (\Exception $e) {
                    Log::channel('wechat_split')->error('Pay notify', [$e->getMessage()]);
                }
                break;
            case 3://手动分账
                try {
                    SplitService::insert_split_log($fatherId, $split_money, $room_number, $pay_type, $orderNo, $handlingFee, $after_split, $user_id, $split_type);//生成分账记录
                    switch ($is_examine) {
                        case 0://不需审核
                            ManualSplitJob::dispatch($arr)->onQueue("ManualSplitJob")->delay(now()->addSeconds(10));
                            break;
                        case 1://需要审核
                            break;
                        default:
                            break;
                    }
                } catch (\Exception $e) {
                    Log::channel('wechat_split')->error('Pay notify', [$e->getMessage()]);
                }
                break;
            default:
                break;
        }

    }

    /**
     * 更新订单后操作
     * @param $param
     */
    public static function update_after($param): void
    {
        extract($param, null);
        /**
         * @var $one_order |订单
         * @var $bill_str |费用类型
         * @var $after_balance |支付后余额
         * @var $owner |业主信息
         */
        try {
            self::unifiedPaymentSend($one_order, $bill_str, $after_balance, $owner);
        } catch (\Exception $e) {
            p($e->getMessage());
        }

    }

    /**
     * @param $openid string  用户的openid
     * @param $order_sn string 商户订单号
     * @param $amount int  付款金额 单位分
     * @param string $desc 付款说明
     * @param null $username 如果传则验证真实姓名
     * @return string | true   如果返回string就是微信返回的错误信息  true === 执行成功
     */
    public static function payment($openid, $order_sn, $amount, $desc = '用户提现', $username = null)
    {
        if (!$openid) {
            return 'openid不能为空';
        }

        //测试设置一分
        $amount = 1;

        $order = [
            'type' => 'miniapp',    // <----必须传递type 使用小程序APPID
            'partner_trade_no' => $order_sn,              //商户订单号
            'openid' => $openid,                        //收款人的openid
            'check_name' => $username ? 'FORCE_CHECK' : 'NO_CHECK',//NO_CHECK：不校验真实姓名;FORCE_CHECK：强校验真实姓名
            're_user_name' => $username,
            'amount' => $amount,
            'desc' => $desc
        ];


        $result = app('wechat_pay_user')->transfer($order);
        return $result;
    }

    /**
     * 2021/3/17--11:31
     * @author:董宗澳
     * @email:2453611300
     * @wechat:DZA74941
     * @QQ:2453611300
     * @web:www.quzha.net
     * @method:changePhone
     * @effect:修改手机号
     */
    public function changePhone(UserService $userService)
    {
        try {
            return $userService->editPhone();
        } catch (\Exception $e) {
            return $this->format_error('修改失败');
        }
    }


    /**
     * 2021/3/18--15:12
     * @author:董宗澳
     * @email:2453611300
     * @wechat:DZA74941
     * @QQ:2453611300
     * @web:www.quzha.net
     * @method:getComments
     * @effect:获取用户评论
     */
    public function getComments(OrderCommentService $ocs)
    {
        try {
            return $ocs->getUserList();
        } catch (\Exception $e) {
            return $this->format_error($e->getMessage());
        }
    }

    /**
     * 2021/3/22--11:30
     * @effect:回调方法处理
     * @param $wxData
     * @author:苏冬冬
     * @QQ:1299273928
     * @method:notify_handle
     */
    public function notify_handle($wxData): void
    {
        $order_model = new ElectricPaymentOrder();
        if ($wxData['result_code'] == 'SUCCESS' && $wxData['return_code'] == 'SUCCESS') {
            $one_order = $order_model->where(['orderNo' => $wxData['out_trade_no']])->first();
            $owner = Users::selectRaw('room_number')->find($one_order->user_id);
            $params = [
                'order_no' => $wxData['out_trade_no'],//订单号
                'pay_price' => $wxData['total_fee'] / 100,//支付金额
                'pay_no' => $wxData['transaction_id'],//支付单号
                'type' => $one_order['pay_type'],//支付方式
            ];
            $update_handle = NotifyService::update($params);
            if ($update_handle) {
                $one_order['room_number'] = $owner->room_number;
                self::split_do($one_order);
                $result = NotifyService::after_notify($one_order);
                NotifyService::update_after($result);
            }
        }
}
}
